import React, { useEffect, useState } from'react';
import axios from 'axios';
import { message } from 'antd'; // 假设使用 antd 的 message 组件，需确保已安装 antd
import w2 from "../../assets/react.svg"
import aaa from "../../assets/react.svg"
// 定义接口返回数据的类型
interface TokenResponse {
    access_token: string;
}

interface TextResponse {
    data: {
        result: string[];
    };
}

interface ChatResponse {
    data: {
        answer: string;
        conversation_id: string;
    };
}

// 定义组件 props 类型
interface Props {}

const Index: React.FC<Props> = (props) => {
    const [speaking, setSpeaking] = useState(false);
    const [list, setList] = useState<any[]>([]);
    const [yytoken, setYyToken] = useState('');
    const [listShow, setListShow] = useState(false);

    // 模拟 recorder 对象，需根据实际情况替换
    const recorder = {
        start: () => console.log('recorder start'),
        stop: () => console.log('recorder stop'),
        getPCMBlob: () => new Blob([], { type: 'audio/pcm' })
    };

    // 模拟 aaa 和 w2 图片路径，需根据实际情况替换
    // 获取 token 的函数
    const getToken = async (): Promise<TokenResponse> => {
        try {
            const response = await axios.post('/getAIToken', {
                app_id: 'f94632e6-e650-41d3-889c-14171687dd09'
            }, {
                headers: {
                    'Content-Type': 'application/json',
                    'X-Appbuilder-Authorization': 'Bearer bce-v3/ALTAK-DJ7QNpQkM4TzQ2YHhjHml/f5756b73ca61bd5035850c35d6f3011bf7abf2a5'
                }
            });
            return response.data;
        } catch (error) {
            console.error('获取 token 失败', error);
            throw error;
        }
    };

    // 调用转文字接口的函数
    const getText = async (token: string, base64data: string, size: number): Promise<TextResponse> => {
        try {
            const response = await axios.post('/转文字接口路径', {
                // 假设接口需要的参数
                token,
                base64data,
                size
            }, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            return response.data;
        } catch (error) {
            console.error('调用转文字接口失败', error);
            throw error;
        }
    };

    // 调用聊天接口的函数
    const chat = async (token: string, myText: string, conversation_id: string): Promise<ChatResponse> => {
        try {
            const response = await axios.post('/chat', {
                app_id: 'f94632e6-e650-41d3-889c-14171687dd09',
                query: myText,
                conversation_id,
                stream: false
            }, {
                headers: {
                    'Content-Type': 'application/json',
                    'X-Appbuilder-Authorization': `Bearer ${token}`
                }
            });
            return response.data;
        } catch (error) {
            console.error('调用聊天接口失败', error);
            throw error;
        }
    };

    const entSpeak = () => {
        setSpeaking(false);
        message.info('讲话结束');
        recorder.stop();
        const babo = recorder.getPCMBlob();
        const reader = new FileReader();
        reader.readAsDataURL(babo);
        reader.onload = async (e) => {
            const base64 = e.target?.result as string;
            const base64data = base64.split(',')[1];
            const res = await getText(yytoken, base64data, babo.size);
            const { data: { result: [myText] } } = res;
            setList((list1) => [...list1, { text: myText, id: Math.random().toString().slice(1, 7), flag: 1 }]);

            const { data: { conversation_id } } = await getToken();
            const { data: chatData } = await chat(yytoken, myText, conversation_id);
            const { answer } = chatData;
            console.log(answer, 'answer');
            setList((l) => [...l, { text: answer, id: Math.random().toString().slice(1, 7), flag: 2 }]);

            const synth = window.speechSynthesis;
            const utterance = new SpeechSynthesisUtterance(answer);
            utterance.lang = 'zh-CN';
            utterance.rate = 1.0;
            synth.onvoiceschanged = () => {
                const voices = synth.getVoices();
                utterance.voice = voices[63];
                synth.speak(utterance);
            };
        };
    };

    const startSpeak = () => {
        setListShow(true);
        setSpeaking(true);
        message.info('正在说话中');
        navigator.mediaDevices.getUserMedia({ audio: true }).then(() => {
            recorder.start();
        });
    };

    useEffect(() => {
        getToken().then((res) => {
            console.log(res,'res11111');
            setYyToken(res.access_token);
        }).catch((err) => {
            console.error(err, 'err');
        });
    }, []);

    return (
        <div className="scoketList" style={{ display: listShow? 'block' : 'none' }}>
            <div className="speakX" onClick={() => setListShow(false)}>
                X
            </div>
            {list.map((item) => {
                return item.flag === 1? (
                    <div key={item.id} className="speak_left">
                        <img src={aaa} alt='' /><span>{item.text}</span>
                    </div>
                ) : (
                    <div key={item.id} className="speak_right">
                        <span>{item.text}</span><img src={w2} alt='' />
                    </div>
                );
            })}
        </div>
    );
};

export default Index;